package com.gqmk.demo.springcloudgatewayzuul.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 *  Zuul 网关拦截器功能
 */
@Component
public class LoginZuulFilter extends ZuulFilter {

    /**
     *  pre：路由前
     *  routing：路由时
     *  post：路由后
     *  error：发送错误调用
     */
    @Override
    public String filterType() {
        return "pre";
    }

    // 过滤顺序
    @Override
    public int filterOrder() {
        return 0;
    }

    // 是否开启此过滤
    @Override
    public boolean shouldFilter() {
        return true;
    }

    // 具体的过滤器业务规则
    @Override
    public Object run() throws ZuulException {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String token = request.getParameter("token");
        if (StringUtils.isBlank(token)) {
            currentContext.setSendZuulResponse(false);
            currentContext.setResponseStatusCode(401);

            HttpServletResponse response = currentContext.getResponse();
            response.setContentType(MediaType.APPLICATION_JSON_UTF8.toString());

            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> map = new HashMap<>();
            map.put("status", 401);
            map.put("message", "LoginZuulFilter验证请求非法！");
            try {
                response.getWriter().write(objectMapper.writeValueAsString(map));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }
}
